import 'package:dss_base/net/base_entity.dart';
import 'package:dss_base/net/http_util.dart';
import 'package:dss_base/widgets/base/base_view_model.dart';
import 'package:dss_base/widgets/base/state_holder.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';

/// 一般用作一进来就需要请求网络的界面中的小界面，如：主页的轮播图，可能是单独一个接口
abstract class BaseFragmentViewModel<T> extends BaseViewModel {
  PageState pageState = PageState.initState;
  T? pageData;

  /// 显示状态页 - 加载中
  void showLoadingPage() {
    pageState = PageState.loadingState;
    setStateChanged();
  }

  /// 显示状态页 - 最终内容
  void showSuccessPage() {
    pageState = PageState.successState;
    setStateChanged();
  }

  /// 显示状态页 - 失败
  void showFailurePage() {
    pageState = PageState.failureState;
    setStateChanged();
  }

  /// 显示状态页 - 空页面
  void showEmptyPage() {
    pageState = PageState.emptyState;
    setStateChanged();
  }

  Future<BaseEntity> onRequestPageData();

  T? onConvertPageData(dynamic json);

  bool onCheckEmpty(BaseEntity entity, T? data);

  void onSuccess(BaseEntity entity, T? data){}

  /// 一进来就需要初始化的数据，一般为网络请求
  void initData() {
    showLoadingPage();
    super.request(
      isShowLoadingDialog: false,
      request: onRequestPageData(),
      onConvert: (json) => json == null ? null : onConvertPageData(json),
      onSuccess: (entity, data) {
        if (onCheckEmpty(entity, data)) {
          showEmptyPage();
        } else {
          pageData = data;
          onSuccess(entity, data);
          showSuccessPage();
        }
      },
      onFailure: (code, msg) => showFailurePage(),
    );
  }

  Future<IndicatorResult> refresh() async {
    BaseEntity entity = await onRequestPageData();
    if (entity.isSuccess) {
      T? data = onConvertPageData(entity.data);
      if (onCheckEmpty(entity, data)) {
        showEmptyPage();
        return IndicatorResult.none;
      } else {
        pageData = data;
        onSuccess(entity, data);
        showSuccessPage();
        return IndicatorResult.success;
      }
    } else {
      return IndicatorResult.fail;
    }
  }
}
